package ru.tests;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

/**
 * TODO: add description
 *
 * @author Alexander Troshanin
 */
public class GrabWaresGroupsFromUtkonos {

    public static void main(String[] args) throws IOException, ClassNotFoundException {

        /* */
        FileInputStream fin = new FileInputStream("src\\main\\database\\wares_groups_lst.ser");
        ObjectInputStream in = new ObjectInputStream(fin);
        Object obj = in.readObject();

        in.close();

        System.exit(111);
        /* */

/*
        String str = String.format("Welcome %10d, %5s, at %50s 111", 14, "Real's HowTo", "http://www.rgagnon.com");
        System.out.println(str);
        System.exit(111);
*/

        System.setProperty("http.proxyHost", "db-isa-01");
        System.setProperty("http.proxyPort", "8080");

//        System.out.println(readUrl("http://www.utkonos.ru/cat/2/"));
        List<WareGroup> roots = readDataLevel1FromUrl("http://www.utkonos.ru/cat/1/");

        roots.add(new WareGroup(1000002002, "Прочее", true));

        for (WareGroup wareGroup : roots) {
            addSecondLevels(wareGroup);
        }

        System.out.println("1");
//        List<WareGroup> roots = readDataLevel2FromUrl("http://www.utkonos.ru/cat/2/");

        recalcIds(roots);

        FileOutputStream fout = new FileOutputStream("src\\main\\database\\wares_groups_lst.ser");
        ObjectOutputStream out = new ObjectOutputStream(fout);
        out.writeObject(roots);

        out.close();
    }

/*
    private static void printSql(List<WareGroup> groups) {
        for (WareGroup group : groups) {

            if (group.parent.utkonosID > 0) {
                "insert into wares_groups values (1,   true,  'Прочее', 100, NULL);";
                System.out.println("insert into REGIONS (ID, NAME, SUPPORT_PRICE_CALC, PARENT_ID) values (" + group.getId() + ", '" + group.getName().replace("'", "''") + "', " + group.isSupportPriceCalc() + ", " + group.getParent().getId() + ");");
            } else {
                System.out.println("insert into REGIONS (ID, NAME, SUPPORT_PRICE_CALC) values (" + group.getId() + ", '" + group.getName().replace("'", "''") + "', " + group.isSupportPriceCalc() + ");");
            }

            printSql(group.childs);
        }
    }
*/


    private static void recalcIds(List<WareGroup> groups) {
        for (WareGroup group : groups) {
            group.id = (int) getNextId();
            recalcIds(group.childs);
        }
    }

    private static long idSequence = 0;
    private static long getNextId() {
        idSequence++;
        return idSequence;
    }

    private static void addSecondLevels(WareGroup wareGroup) throws IOException {

        List<WareGroup> roots = readDataLevel2FromUrl("http://www.utkonos.ru/cat/" + wareGroup.utkonosID +  "/");
        for (WareGroup wg : roots) {
            wareGroup.addChild(wg);
        }

    }

    private static String readUrl(String urlstr) throws IOException {
        URL url = new URL(urlstr);
        URLConnection connection = url.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;

        StringBuilder result = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            result.append(inputLine).append("\n");
            //System.out.println(inputLine);
        }
        in.close();
        return result.toString();
    }

    private static List<WareGroup> readDataLevel1FromUrl(String urlstr) throws IOException {
        URL url = new URL(urlstr);
        URLConnection connection = url.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;

        List<WareGroup> roots = new ArrayList<WareGroup>();
        while ((inputLine = in.readLine()) != null) {

            int i0 = inputLine.indexOf("<span></span></a><a class=\" link");
            if (i0 != -1) {

                inputLine = inputLine.substring(i0);

                int i1 = inputLine.indexOf("href=\"/cat/");
                int i2 = inputLine.indexOf("/\">");
                String idStr = inputLine.substring(i1 + "href=\"/cat/".length(), i2);

//                int i3 = inputLine.indexOf("<span></span>");
                int i3 = inputLine.lastIndexOf("<span></span>");

                String name = inputLine.substring(i2 + "/\">".length(), i3);

                try {
                    roots.add(new WareGroup(Integer.parseInt(idStr), name));
                } catch (NumberFormatException e) {
                    
                }
            }
        }
        in.close();
        return roots;
    }

    private static List<WareGroup> readDataLevel2FromUrl(String urlstr) throws IOException {
        URL url = new URL(urlstr);
        URLConnection connection = url.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;

        WareGroup currentWareRoot = null;
        StringBuilder result = new StringBuilder();
        List<WareGroup> roots = new ArrayList<WareGroup>();
        while ((inputLine = in.readLine()) != null) {

//            if (inputLine.startsWith("<a class=\"subtree last first\"")) {
            if (inputLine.indexOf("<a class=\"subtree last first\"") != -1) {
                int i1 = inputLine.indexOf("href=\"/cat/");
                int i2 = inputLine.indexOf("/\">");
                String idStr = inputLine.substring(i1 + "href=\"/cat/".length(), i2);

                int i3 = inputLine.indexOf("<span></span>");

                String name = inputLine.substring(i2 + "/\">".length(), i3);
                System.out.println(idStr + " - " + name);
                try {
                    int idInt = Integer.parseInt(idStr);
                    currentWareRoot = new WareGroup(idInt, name);
                    roots.add(currentWareRoot);
                } catch (NumberFormatException e) {
                    
                }
            } else {
                if (currentWareRoot != null) {

                    if (inputLine.trim().startsWith("<a class=\"cat_link")) {
                        int i1 = inputLine.indexOf("href=\"/cat/");
                        int i2 = inputLine.indexOf("/\">");
                        String idStr = inputLine.substring(i1 + "href=\"/cat/".length(), i2);
                        int i3 = inputLine.indexOf("<span></span>");
                        String name = inputLine.substring(i2 + "/\">".length(), i3);

                        try {
                            currentWareRoot.addChild(new WareGroup(Integer.parseInt(idStr), name));
                        } catch (NumberFormatException e) {
                        }
                    }

                }

            }

//            result.append(inputLine).append("\n");
            //System.out.println(inputLine);
        }
        in.close();
        return roots;
    }

}


class WareGroup implements Serializable {

    private static final long serialVersionUID = 1554891668379925793L;

    int id;
    int utkonosID;
    String name;
    WareGroup parent;
    boolean defaultGroup;

    ArrayList<WareGroup> childs = new ArrayList<WareGroup>();

    ArrayList<WareUtkonos> wares = new ArrayList<WareUtkonos>();

    WareGroup(int id, String name) {
        this(id, name, false);
    }

    WareGroup(int id, String name, boolean defaultGroup) {
        this.utkonosID = id;
        this.name = name;
        this.defaultGroup = defaultGroup;
    }

    public void addChild(WareGroup child) {
        childs.add(child);
        child.parent = this;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append("WareGroup");
        sb.append("{id=").append(id);
        sb.append(", utkonosID=").append(utkonosID);
        sb.append(", name='").append(name).append('\'');
        sb.append('}');
        return sb.toString();
    }
}

class WareUtkonos implements Serializable {

    int utkonosID;

    String name;

    String price;

    String imgUrl;

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append("WareUtkonos");
        sb.append("{utkonosID=").append(utkonosID);
        sb.append(", name='").append(name).append('\'');
        sb.append(", price='").append(price).append('\'');
        sb.append('}');
        return sb.toString();
    }
}